﻿using System;
using System.Data;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Management;

namespace Utils
{
   public class ToolUtility
   {

       /// <summary>
       /// 全部填充为空白行
       /// </summary>
       /// <param name="rowNum"></param>
       ///// <returns></returns>
       //public static DataTable FillBlankRows(int rowNum)
       //{
       //    DataTable dt = new DataTable();

       //    for (int i = 0; i < rowNum; i++)
       //            {
       //                DataRow dr = dt.NewRow();
       //                dt.Rows.Add(dr);
       //            }
       //    return dt;

       //}
     
       #region 页脚统计
       /// <summary>
       /// ReturnTotal 统计gridview列
       /// </summary>
       /// <param name="gvList"></param>
       /// <param name="col"></param>
       /// <returns></returns>
       /*使用方法 
         if (e.Row.RowType == DataControlRowType.Footer)
            {

                int cols = gvList.HeaderRow.Cells.Count-1;
                 for (int i = 5; i <= cols; i++)
                 {
                     e.Row.Cells[0].Text = "合计";
                     e.Row.Cells[2].Text =gvList.Rows.Count+ "人";
                     e.Row.Cells[i].Text =Utils.ToolUtility.ReturnTotal(gvList,i).ToString();
                 }                
            }
        * */
           public static decimal ReturnTotal(GridView gvList, int col)
       {
           decimal char_total = 0;
           foreach (GridViewRow gvr in gvList.Rows)
           {
               if (gvr.RowType == DataControlRowType.DataRow)
               // if (null != gvr.Cells[col].Text)
               {
                   string str = gvr.Cells[col].Text.Trim();
                   if (!string.IsNullOrWhiteSpace(str) && str != "&nbsp;")
                   {
                       char_total += Convert.ToDecimal(str);
                   }
               }
           }
           return char_total;
       }
       #endregion
           /// <summary>
       /// 文本框设置为只读
       /// </summary>
       /// <param name="tb">文本框</param>
       /// <param name="flag">true：只读</param>
       public static void TextBoxReadOnly(TextBox tb, bool flag)
       {
           if (flag)
           {
               tb.ReadOnly = true;
               tb.BackColor =  System.Drawing.Color.Gray;
           }
           else
           {
               tb.ReadOnly = false;
               tb.BackColor = System.Drawing.Color.White;
           }
       }

        #region 打印
       public static void CrearePdfDoc( DataSet ds, string headerText, string footerText)
       {
           try
           {
               Document document = new Document();
               PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(System.Web.HttpContext.Current.Server.MapPath("~/log/Chap0101.pdf"), FileMode.Create));
               document.Open();                

               BaseFont bfChinese = BaseFont.CreateFont("C:\\WINDOWS\\Fonts\\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
               Font fontChinese = new Font(bfChinese, 12, Font.NORMAL, new BaseColor(0, 0, 0));

              //document.Add(new Paragraph(this.TextBox1.Text.ToString(), fontChinese));
             //  iTextSharp.text.Image jpeg = iTextSharp.text.Image.GetInstance(Server.MapPath("pic015.jpg"));
            //   document.Add(jpeg);
               DataTable datatable = ds.Tables[0];
               PdfPTable table = new PdfPTable(datatable.Columns.Count);
               for (int i = 0; i < datatable.Rows.Count; i++)
               {
                   for (int j = 0; j < datatable.Columns.Count; j++)
                   {
                       table.AddCell(new Phrase(datatable.Rows[i][j].ToString(),fontChinese));
                   }
               }
               document.Add(table);
               document.Close();
               writer.Close();
           }
           catch (DocumentException ee)
           {
               LogHelper.WriteLog("从配置文件获取要显示的字段出错。", ee); 
           }
       }

       /// <summary>
        /// 打印gridview
        /// 使用方式：方法调用
        /// </summary>
        /// <param name="strTitle">标题</param>
        /// <param name="gvID">GridView的ID</param>
        public static void Printer(string strTitle,GridView gvID)
        {
            GoldPrinter.MisGoldPrinter webmis = new GoldPrinter.MisGoldPrinter();
            webmis.Title = strTitle;  //标题，还可设置子标题
            //(webmis.Title as GoldPrinter.Title).Font = new System.Drawing.Font("宋体", 12, System.Drawing.FontStyle.Bold);
            (webmis.Body as GoldPrinter.Body).DataSource = ToStringArray(gvID, true);

            //为人特性化，自定义表体，可以设置字体、列宽、列对齐方式
           // GoldPrinter.Body gridBody = new GoldPrinter.Body();
            //任意二维的数据通通打印，或者是设置GridText属性
           // gridBody.DataSource = ToStringArray(gvID, true);          
           // webmis.Body = gridBody;


            webmis.Preview();
            webmis.Dispose();
        }
        /// <summary>
        /// 将GridView控件的数据导出到二维数组。
        /// </summary>
        /// <param name="dataGridView">VS.Net 2005 DataGridView控件。</param>
        /// <param name="includeColumnText">是否要把列标题文本也导到数组中。</param>
        /// <returns>二维数组。</returns>
        /// </summary>
        protected static string[,] ToStringArray(GridView dataGridView, bool includeColumnText)
        {
            string[,] arrReturn = null;
            int rowsCount = dataGridView.Rows.Count;
            int colsCount = dataGridView.Columns.Count;
            int i = 0;

            //包括列标题
            if (includeColumnText)
            {
                rowsCount++;
                arrReturn = new string[rowsCount, colsCount];
                for (i = 0; i < colsCount; i++)
                {
                    arrReturn[0, i] = dataGridView.Columns[i].HeaderText;
                }
                i = 1;
            }
            else
            {
                arrReturn = new string[rowsCount, colsCount];
            }

            //读取单元格数据
            int rowIndex = 0;
            for (; i < rowsCount; i++, rowIndex++)
            {
                for (int j = 0; j < colsCount; j++)
                {
                    arrReturn[i, j] = dataGridView.Rows[rowIndex].Cells[j].Text.Trim();
                }
            }

            return arrReturn;
        }

       #endregion

        #region 加解密
        //MD5加密字符串
        public static string MD5Encrypt(string strText)
        {
            byte[] buffer1 = new MD5CryptoServiceProvider().ComputeHash(Encoding.Unicode.GetBytes(strText));
            StringBuilder builder1 = new StringBuilder();
            foreach (byte num1 in buffer1)
            {
                builder1.Append(num1.ToString("x2").ToLower());
            }
            return builder1.ToString();
        }
        
      
        #endregion
        
  


       #region 获取硬件信息
        public static string GetIPAddress()
        {
            string ipAddress = string.Empty;
            System.Net.IPHostEntry ipHostEntrys = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
            foreach (System.Net.IPAddress ip in ipHostEntrys.AddressList)
            {
                ipAddress = ip.ToString();
            }
            return ipAddress;
        }

        public static string GetCPUSerialNo()
        {
            string cpuSerialNo = string.Empty;
            ManagementClass managementClass = new ManagementClass("Win32_Processor");
            ManagementObjectCollection managementObjectCollection = managementClass.GetInstances();
            foreach (ManagementObject managementObject in managementObjectCollection)
            {
                // 可能是有多个
                cpuSerialNo = managementObject.Properties["ProcessorId"].Value.ToString();
                break;
            }
            return cpuSerialNo;
        }

        public static string GetHardDiskInfo()
        {
            string hardDisk = string.Empty;
            ManagementClass managementClass = new ManagementClass("Win32_DiskDrive");
            ManagementObjectCollection managementObjectCollection = managementClass.GetInstances();
            foreach (ManagementObject managementObject in managementObjectCollection)
            {
                // 可能是有多个
                hardDisk = (string)managementObject.Properties["Model"].Value;
                break;
            }
            return hardDisk;
        }

        public static string GetMacAddress()
        {
            string macAddress = string.Empty;
            ManagementClass managementClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection managementObjectCollection = managementClass.GetInstances();
            foreach (ManagementObject managementObject in managementObjectCollection)
            {
                // 可能是有多个
                if ((bool)managementObject["IPEnabled"] == true)
                {
                    macAddress = managementObject["MacAddress"].ToString();
                    break;
                }
            }
            return macAddress;
        }

       #endregion

   }
}
